﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kelper.Infrastructure.Abstract;
using Kelper.Domain.Models;

namespace Kelper.Infrastructure
{
    public class StoredFile
    {
        public string FullName { get; set; }
        public string Extension { get; set; }
        public string ContentType { get; set; }

        public StoredFile() { }

        public StoredFile(string fileName)
        {
            FullName = fileName;
            Extension = new FileInfo(fileName).Extension;
            ContentType = LocalRecipeImageStore.ContentTypes[Extension.ToLower()];
        }
    }

    public class LocalRecipeImageStore
    {
        public static readonly string[] AllowedExtensions = { ".jpg", ".jpeg", ".png", ".bmp" };
        public static readonly Dictionary<string, string> ContentTypes = new Dictionary<string, string>
        {
            { ".jpg", "image/jpeg" },
            { ".jpeg", "image/jpeg" },
            { ".png", "image/png" },
            { ".bmp", "image/x-ms-bmp" }
        };

        private string folder;

        public LocalRecipeImageStore(string folder)
        {
            this.folder = folder;
        }

        public void Save(Recipe recipe, HttpPostedFileBase file)
        {
            if (file != null)
            {
                string fullName = Path.Combine(folder, recipe.ID + new FileInfo(file.FileName).Extension);

                DeleteIfExistsAny(recipe.ID);
                file.SaveAs(fullName);
            }
        }

        public bool IsValidFileExtension(HttpPostedFileBase file)
        {
            return file == null || AllowedExtensions.Any(e => file.FileName.ToLower().EndsWith(e));
        }

        public StoredFile Get(int id)
        {
            if (!Directory.Exists(folder))
                return null;

            foreach (string file in Directory.GetFiles(folder))
                if (new FileInfo(file).Name.StartsWith(id + "."))
                    return new StoredFile(file);
            return null;
        }

        public void Remove(int id)
        {
            DeleteIfExistsAny(id);
        }

        private void DeleteIfExistsAny(int id)
        {
            StoredFile file = Get(id);
            if (file != null)
                File.Delete(file.FullName);
        }
    }
}